<template>
  <div>
    <div class="box">

     <!-- <el-form-item prop="imgUrl" :rules="imgUrlRules">

      </el-form-item> -->
       <el-upload
         class="avatar-uploader"
         :auto-upload="false"
         action="#"
         :file-list="fileList"
         :limit="1"
         :show-file-list="false"
         :on-change="handleAvatarSuccess"
         :before-upload="beforeAvatarUpload">
         <img v-if="imgUrl" :src="imgUrl" class="avatar">
         <div v-else>
           <i class="el-icon-plus avatar-uploader-icon"></i>
           <!-- <div class="text-upload">点击上传</div> -->
         </div>
       </el-upload>
      <div class="text-tip">（只能上传jpg/png文件，且不超过500kb）</div>
    </div>
  </div>
</template>

<script>
  import { uploadFile } from "@/api/messages/eventManage";
  export default {
    data() {
      //定义校验规则
      // let validateFileUrl = (rule, value, callback) => {
      //   if (this.fileList.length < 1) {
      //       callback(new Error("请上传文件"))
      //   } else {
      //       callback()
      //   }
      // }
      return {
        imgUrl: '',
        fileList: [],
        // imgUrlRules: [
        //   { required: true,validator: validateFileurl, trigger: 'change' }
        // ]
      }
    },
    methods: {
      // 上传图片
      handleAvatarSuccess(res, file) {
       let formData = new FormData();
       formData.append('file', file[0].raw);
        uploadFile(formData).then(res => {
          this.imgUrl = res.data;
          this.$emit('imgUrl', this.imgUrl); // 触发事件，将imgUrl传递给父组件
          this.fileList = [];
        })
      },
      beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt500kb = file.size / 1024 < 500;

        if (!isJPGorPNG) {
          this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
        }
        if (!isLt500kb) {
          this.$message.error('上传头像图片大小不能超过 500kb!');
        }
        return isJPGorPNG && isLt500kb;
      },
    }
  }
</script>

<style lang="scss" scoped>
  .box{
    display: flex;
    align-items: center;
    .avatar-uploader {
      width: 90px;
      height: 90px;
      background: #F5F5F6;
      border-radius: 5px;
      border: 1px dashed #B5B5B5;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      display: flex;
      justify-content: center;
      align-items: center;
      .text-upload {
        position: absolute;
      }
      .avatar {
        width: 90px;
        height: 90px;
        object-fit: cover;
        transform: translateY(6px);
        background: #F5F5F6;
        border-radius: 5px;
        border: 1px solid #B5B5B5;
        // width: 178px;
        // height: 178px;
        // display: block;
      }
    }
    .text-tip {
      font-weight: 400;
      font-size: 14px;
      color: #999999;
    }
  }
</style>
